package com.ubxtech.web.utils;

import cn.hutool.core.util.StrUtil;
import com.ubxtech.core.context.Result;
import com.ubxtech.core.utils.SpringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.lang.Nullable;

/**
 *
 * @author Victor.Xiao
 * @since 2023-08-14 20:55
*/
public class LocaleUtil {

    public static MessageSource messageSource;

    public static MessageSource getMessageSource(){
        if (messageSource == null) {
            if (SpringUtils.hasBean("nacosStaticMessageSource")) {
                messageSource = (MessageSource) SpringUtils.getBean("nacosStaticMessageSource");
            } else {
                messageSource = SpringUtils.getBean(MessageSource.class);
            }
        }
        return messageSource;
    }


    //---------------------------------------------------------------------
    // Implementation of MessageSource interface
    //---------------------------------------------------------------------

    public static String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage) {
        return getMessageSource().getMessage(code, args, defaultMessage, LocaleContextHolder.getLocale());
    }
    public static String getMessage(String code, @Nullable String defaultMessage) {
        return getMessageSource().getMessage(code, null, defaultMessage, LocaleContextHolder.getLocale());
    }

    public static String getMessage(String code) throws NoSuchMessageException {
        if (StrUtil.isBlank(code)) {
            return code;
        }
        return getMessageSource().getMessage(code, null, LocaleContextHolder.getLocale());
    }

    public static String getMessage(String code, @Nullable Object[] args) throws NoSuchMessageException {
        if (StrUtil.isBlank(code)) {
            return code;
        }
        return getMessageSource().getMessage(code, args, LocaleContextHolder.getLocale());
    }

    public static String getMessage(MessageSourceResolvable resolvable) throws NoSuchMessageException {
        return getMessageSource().getMessage(resolvable, LocaleContextHolder.getLocale());
    }


    public static void replaceI18n(Result<?> result) {
        if (result != null) {
//            String msg = LocaleUtil.getMessage(result.getMsg(),LocaleUtil.getMessage("error_"+result.getCode(),result.getMsg()));
            String msg = LocaleUtil.getMessage(result.getMsg(), "");
            if (StrUtil.isBlank(msg)) {
                msg = LocaleUtil.getMessage("api.error."+result.getCode(), "");
            }
            if (StrUtil.isNotBlank(msg)) {
                result.setMsg(msg);
            }
        }
    }

}
